<template>
  <div class="list-table">
    <div class="area-header">
      <span class="area-header-title">{{ $t('财务数据') }}</span>
    </div>

    <pcwDataBaseReportImport ref="pcwDataBaseReportImport" :is-show-query-btn="true" :view-table="view_table" :class="[importOpen ? 'custom-vue' : '']" @importMethod="importMethod" @queryParam="queryParam" />

    <el-tabs v-model="view_table" :before-leave="beforeLeave" @tab-click="tab_click">
      <el-tab-pane :label="$t('资产负债表')" name="balance_sheet" />
      <el-tab-pane :label="$t('利润表')" name="income_sheet" />
      <el-tab-pane :label="$t('现金流量表')" name="cash_flow_sheet" />
      <el-tab-pane :label="$t('关键指标')" name="pcw_report" />
    </el-tabs>

    <div v-loading="loading" :style="{ overflow: 'auto', 'height': (windowHeight + 20) + 'px' }">
      <el-table
        ref="scrollTable"
        :data="pcwDataBaseList"
        border
        class="el-table__body-wrapper is-scrolling-right"
        :height="windowHeight"
        :span-method="objectSpanMethod"
      >
        <el-table-column
          v-for="(col) in pcwColumns"
          :key="col.prop"
          :prop="col.prop"
          :label="(col.labelSource ? ($t(col.label) + '-' + ($t(col.labelYear) + '-' + $t(col.labelType) + '('+$t(col.labelSource)+')')) : $t(col.label))"
          :fixed="col.prop === 'subjectName' || col.prop === 'keyReport'"
          :width="'240'"
        >
          <template slot-scope="scope">
            <span v-if="col.prop === 'keyReport' && view_table === 'pcw_report'">
              {{ $t(scope.row[col.prop]) }}
            </span>
            <span v-else-if="col.prop === 'subjectName'">
              {{ $t(scope.row[col.prop]) }}
            </span>
            <span v-else-if=" view_table !== 'pcw_report'">
              <span v-if="scope.row !== undefined && scope.row[col.prop] !== undefined && scope.row[col.prop].list !== undefined">
                <span v-for="(row, indexRow) in scope.row[col.prop].list" :key="col.prop + '_' + indexRow">
                  <span v-if="row.keyCode === scope.row.keyCode">
                    {{ showNumber((row.keyValue)) }}
                  </span>
                </span>
              </span>
            </span>
            <span v-else-if=" view_table === 'pcw_report'">
              <span v-if="scope.row[col.prop] !== undefined && scope.row[col.prop].val !== undefined">
                {{ moneyFormat(scope.row[col.prop].val) }}
              </span>
            </span>
          </template>
        </el-table-column>
      </el-table>
      <div v-if="isLoadingPage" style="text-align: right;width: 100%;z-index: 2002;margin: -40px;">
        <i class="el-icon-loading" />
      </div>
    </div>

    <!-- 导出 -->
    <el-dialog :title="$t('导出')" :visible.sync="importOpen" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogView" append-to-body>
      <div>
        <pcwDataBaseReportImport ref="pcwDataBaseReportImport" :is-show-query-btn="false" :view-table="view_table" />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import pcwDataBaseReportImport from '@/views/deal/report/pcw/pcwDataBaseReportImport.vue'
import { listGroupPcwDataBaseReport, queryDataByDealId } from '@/api/company/pcw/pcwDataBase'
export default {
  components: {
    pcwDataBaseReportImport
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      loadingData: false,
      importOpen: false,
      // 财务数据基础数据集合
      pcwDataBaseList: [],
      pcwColumns: [],
      dataSourceOptions: [],
      dealBaseListOption: [],
      fundBaseListOption: [],
      // 查询参数
      queryParams: {
        queryCriteria: [],
        financialTemplate: undefined,
        yearS: undefined,
        dealIdList: undefined,
        fundIdList: undefined,
        dataSourceList: undefined,
        type: undefined
      },
      total: 0,
      pageNum: 1,
      pageSize: 7,
      // 表单参数
      form: {},
      // 报告类型
      typeOptions: [],
      // 表单校验
      rules: {},
      // 表格tab
      view_table: 'balance_sheet',
      // 修改基础数据提交后台
      dataBaseForm: {},
      // 财务模板下拉
      financialTemplateOptions: [],
      queryRules: {
        financialTemplate: [{ required: true, message: this.$t('必填信息'),	trigger: 'change' }],
        yearS: [{ required: true, message: this.$t('必填信息'),	trigger: 'change' }],
        type: [{ required: true, message: this.$t('必填信息'),	trigger: 'change' }],
        dataSourceList: [{ required: true, message: this.$t('必填信息'),	trigger: 'change' }]
      },
      dealTreeOption: [{ id: 'company', label: 'Company 🏢' }, { id: 'company2', label: 'Company2' }, { id: 'company3', label: 'Company3' }],
      isLoadingPage: false,
      windowHeight: document.documentElement.clientHeight - 390 // 实时屏幕高度
    }
  },
  watch: {
  },
  created() {
  },
  mounted() {
    var that = this
    // <!--把window.onresize事件挂在到mounted函数上-->
    window.onresize = () => {
      return (() => {
        that.windowHeight = document.documentElement.clientHeight - 380 // 高
      })()
    }
  },
  methods: {
    getList() {
      this.pcwDataBaseList = []
      this.pcwColumns = []
      this.loading = true
      this.pageNum = 1
      this.pageSize = 7
      this.total = 0
      this.getListStart()
    },
    /** 查询上传财务数据主表列表 */
    getListStart() {
      if ((this.total + (this.view_table !== 'pcw_report' ? 1 : 2)) === this.pcwColumns.length && this.total !== 0) {
        this.isLoadingPage = false
      } else {
        this.loading = true
        this.queryParams.belongsTable = this.view_table
        if (this.queryParams.dealIdList.length > 0) {
          this.queryParams.fundIdList = []
        }
        this.queryParams.pageNum = this.pageNum
        this.queryParams.pageSize = this.pageSize
        listGroupPcwDataBaseReport(this.queryParams).then(response => {
          if (response.data !== null) {
            this.total = response.data.total
            if (this.pageNum === 1) {
              this.pcwDataBaseList = response.data.data
              this.pcwColumns = response.data.columns
              // 遍历获取数据
              this.initDataList()
            } else {
              if (this.view_table !== 'pcw_report') {
                response.data.columns.forEach(item => {
                  if (item.prop !== 'subjectName' && item.prop !== 'keyReport') {
                    this.pcwColumns.push(item)
                  }
                })
                // 遍历获取数据
                this.initDataList()
              } else {
                // 关键指标
                response.data.columns.forEach(item => {
                  if (item.prop !== 'subjectName' && item.prop !== 'keyReport') {
                    this.pcwColumns.push(item)
                  }
                })
                // keyCode
                // keyReport
                // subjectName
                response.data.data.forEach(item => {
                  if (item['subjectName'] !== undefined && item['keyReport'] !== undefined) {
                    this.pcwDataBaseList.forEach(sub => {
                      if (item['keyReport'] === sub['keyReport'] && item['subjectName'] === sub['subjectName']) {
                        for (var i in item) {
                          if (i !== 'keyReport' && i !== 'subjectName' && i !== 'keyCode') {
                            sub[i] = item[i]
                          }
                        }
                      }
                    })
                  }
                })
                this.initDataEnd()
              }
            }
          } else {
            this.loading = false
          }
        })
      }
    },
    initDataList() {
      var start = (this.pageNum - 1) * this.pageSize
      var end = this.pageSize * this.pageNum
      this.pcwColumns.forEach((item, index) => {
        if ((start <= index && index < end)) {
          if (item.prop !== 'subjectName' && item.prop !== 'keyReport') {
            const prop = item.prop.split('_')
            const query = {
              yearS: item.labelYear,
              type: item.labelType,
              dealIdList: [prop[0]],
              dataSourceList: [prop[1]],
              belongsTable: this.view_table,
              queryCriteria: this.queryParams.queryCriteria,
              financialTemplate: this.queryParams.financialTemplate
            }
            // 将模板也传过去
            queryDataByDealId(query).then(response => {
              if (response.data !== null) {
                response.data.forEach(sub => {
                  this.pcwDataBaseList.forEach(sub2 => {
                    // sub2[sub.mainId + '_' + sub.dataSource] = sub
                    this.$set(sub2, [sub.mainId + '_' + sub.dataSource], sub)
                  })
                })
              } else {
                this.loading = false
              }
              if (index <= (end - 1)) {
                this.$forceUpdate()
                setTimeout(() => {
                  this.$nextTick(() => {
                    this.initDataEnd()
                  })
                }, 1000)
              }
            })
          }
        }
      })
    },
    initDataEnd() {
      this.loading = false
      this.isLoadingPage = false
      this.$forceUpdate()
      this.initLoadAddPage()
    },
    initLoadAddPage() {
      // 滑动翻页
      this.$refs.scrollTable.bodyWrapper.addEventListener('scroll', (res) => {
        const height = res.target
        const clientWidth = height.clientWidth
        const scrollWidth = height.scrollWidth
        const scrollLeft = height.scrollLeft
        if (scrollLeft > (scrollWidth - clientWidth - 100) && scrollLeft !== 0) {
          if (!this.isLoadingPage && !((this.total + (this.view_table !== 'pcw_report' ? 1 : 2)) === this.pcwColumns.length && this.total !== 0)) {
            this.isLoadingPage = true
            this.pageNum++
            this.getListStart()
          }
        }
      }, true)
    },
    showNumber(val) {
      return this.moneyFormat(val)
    },
    // 切换页签操作
    tab_click(tab) {
      if (!this.isEmpty(this.queryParams.financialTemplate) && !this.isEmpty(this.queryParams.yearS) && !this.isEmpty(this.queryParams.type) && !this.isEmpty(this.queryParams.dataSourceList) && !this.loading) {
        this.view_table = tab.name
        this.getList()
      }
    },
    beforeLeave() {
      return !this.loading
    },
    queryParam(data) {
      this.queryParams = data
      console.log('查询条件', this.queryParams)
      this.getList()
    },
    importMethod(data) {
      this.importOpen = true
      this.$nextTick(() => {
        this.$refs.pcwDataBaseReportImport.queryParams = data
        this.$refs.pcwDataBaseReportImport.getList()
      })
    },
    isEmpty(val) {
      return val === undefined || val === null || val === ''
    },
    objectSpanMethod({ rowIndex, columnIndex }) {
      if (columnIndex === 0 && this.view_table === 'pcw_report') {
        const spanArr = this.rowspan()
        for (let i = 0; i < spanArr.length; i++) {
          const _row = spanArr[rowIndex]
          return {
            rowspan: _row,
            colspan: 1
          }
        }
      }
    },
    rowspan() {
      // 二维数组，用于存放单元格合并规则
      const spanArr = []
      // 用于存储相同项的开始index
      let position = 0
      this.pcwDataBaseList.forEach((item, index) => {
        if (index === 0) {
          spanArr.push(1)
          position = 0
        } else {
          if (this.pcwDataBaseList[index].keyReport === this.pcwDataBaseList[index - 1].keyReport) {
            spanArr[position] += 1 // 有相同项
            spanArr.push(0) // 名称相同后往数组里面加一项0
          } else {
            spanArr.push(1) // 同列的前后两行单元格不相同
            position = index
          }
        }
      })
      return spanArr
    }
  }
}
</script>
<style lang="scss" scoped>
.custom-vue {
  height: 600px !important;
}
/deep/ .el-dialog .commentsDigOnly {
  width: 75%;
  height: 750px !important;
}
/deep/ .commentsDigOnly {
  width: 75%;
  height: 750px !important;
}
</style>
